package com.jumi.microservice.service.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.dto.admin.WalletAccountList;
import com.jumi.microservice.dto.admin.WalletAccountRequest;
import com.jumi.microservice.dto.admin.WalletAccountResponse;
import com.jumi.microservice.dto.export.WalletAccountExport;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.dto.request.FenXiaoQueryRequest;
import com.jumi.microservice.dto.request.FenxiaoUserQueryRequest;
import com.jumi.microservice.dto.request.JmUserQueryRequest;
import com.jumi.microservice.dto.wallet.api.WalletUserRequest;
import com.jumi.microservice.enumerate.WalletTypeEnum;
import com.jumi.microservice.enums.FenXiaoStatus;
import com.jumi.microservice.mapper.UserCashMapper;
import com.jumi.microservice.mapper.UserWalletMapper;
import com.jumi.microservice.service.IFenXiaoService;
import com.jumi.microservice.service.ILevelConfigService;
import com.jumi.microservice.service.IMemberService;
import com.jumi.microservice.service.IOrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mazhao
 * @Date 2020-07-07 18:16
 */
@Service
public class WalletAccountService {

    @Resource
    UserWalletMapper userWalletMapper;
    @Resource
    UserCashMapper userCashMapper;
    @DubboReference
    ILevelConfigService iLevelConfigService;
    @DubboReference
    IOrderService orderClient;
    @DubboReference
    IFenXiaoService iFenXiaoService;
    @DubboReference
    IMemberService iMemberService;

    public WalletAccountResponse accountList(WalletAccountRequest request) {
        WalletAccountResponse walletAccountResponse = new WalletAccountResponse();
        List<WalletAccountList> result = new ArrayList<>();
        boolean f = false;
        //请求用户模块接口获取会员相关信息
        JmUserQueryRequest jmUserQueryRequest = new JmUserQueryRequest();
        if(request.getPhoneNum()!=null && !request.getPhoneNum().trim().isEmpty()){
            jmUserQueryRequest.setMobile(request.getPhoneNum());
            f = true;
        }
        if (request.getMemberLevel() != null) {
            jmUserQueryRequest.setLevel(request.getMemberLevel());
            f = true;
        }
        jmUserQueryRequest.setClient("wallet");
        Page<JmUserReponse> page = iMemberService
                .getMemberByRequest(jmUserQueryRequest, request.getPageNum(), request.getPageSize()).getData();
        List<JmUserReponse> userResponseList = page.getRecords();
        if (userResponseList.isEmpty()) {
            walletAccountResponse.setWaitIncome(BigDecimal.ZERO);
            walletAccountResponse.setWaitCash(BigDecimal.ZERO);
            walletAccountResponse.setCheckingCash(BigDecimal.ZERO);
            walletAccountResponse.setRows(result);
            walletAccountResponse.setTotal(0L);
            return walletAccountResponse;
        }
        String userIdList = userResponseList.stream().map(j -> j.getId().toString()).collect(Collectors.joining(","));
        //已提现金额
        List<Map<String, Object>> alreadyCashList = userWalletMapper.AlreadyCashByUserIdList(userIdList);
        //审核中金额
        List<Map<String, Object>> checkingCashList = userCashMapper.checkingCashByUserIdList(userIdList);
        //可提现金额
        List<Map<String, Object>> waitCashList = userWalletMapper.waitCashByUserIdList(userIdList);
        //请求接口获取待到账金额
//        Map<Integer, BigDecimal> map = waitIncomeMap(userIdList);
        //获取自购省
        List<Map<String,Object>> selfSaveMap = orderClient.selfSave(userIdList);
        Map<Integer,Object> levelMap = memberLevel();
        for (JmUserReponse jmUserReponse : userResponseList) {
            WalletAccountList response = new WalletAccountList();
            response.setRegisterTime( Date.from(jmUserReponse.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
            response.setMemberCoverImg(jmUserReponse.getAvatar());
            response.setMemberId(jmUserReponse.getId().longValue());
            response.setNickName(jmUserReponse.getName());
            response.setRealName(jmUserReponse.getTruename());
            response.setMemberLevel("");
            if(levelMap.containsKey(jmUserReponse.getLevel().getValue())){
                response.setMemberLevel(levelMap.get(jmUserReponse.getLevel().getValue()).toString());
            }
            response.setPhoneNum(jmUserReponse.getMobile());
            BigDecimal alreadyCash = getDataFromMap(alreadyCashList, jmUserReponse.getId().longValue());
            BigDecimal checking = getDataFromMap(checkingCashList, jmUserReponse.getId().longValue());
            response.setAlreadyCash(alreadyCash.subtract(checking));
            response.setChecking(checking);
            response.setWaitCash(getDataFromMap(waitCashList, jmUserReponse.getId().longValue()));
            response.setWaitIncome(BigDecimal.ZERO);
//            if (map.containsKey(jmUserReponse.getId())) {
//                response.setWaitIncome(map.get(jmUserReponse.getId()));
//            }
            response.setAmount(response.getAlreadyCash().add(response.getChecking()).add(response.getWaitCash()).add(response.getWaitIncome()));
            response.setSelfSave(getDataFromMap(selfSaveMap,jmUserReponse.getId().longValue()));
            result.add(response);
        }
//        if (request.getPageSize() != Integer.MAX_VALUE) {
//            if(f){
//                walletAccountResponse = statistics(request, walletAccountResponse,userIdList);
//            }else{
//                walletAccountResponse = statistics(request, walletAccountResponse,null);
//            }
//            walletAccountResponse.setTotal(page.getTotal());
//        }
        walletAccountResponse.setCheckingCash(BigDecimal.ZERO);
        walletAccountResponse.setWaitCash(BigDecimal.ZERO);
        walletAccountResponse.setWaitIncome(BigDecimal.ZERO);
        walletAccountResponse.setRows(result);
        walletAccountResponse.setTotal(page.getTotal());
        return walletAccountResponse;
    }

    /**
     * 统计
     *
     * @param request
     * @param walletAccountResponse
     * @return
     */
    public WalletAccountResponse statistics(WalletAccountRequest request, WalletAccountResponse walletAccountResponse,String userIdList) {
        BigDecimal waitCash = userWalletMapper.totalWaitCash(userIdList);
        BigDecimal checkingCash = userCashMapper.totalCheckMoney(userIdList);
        FenXiaoQueryRequest fenXiaoQueryRequest = new FenXiaoQueryRequest();
        FenxiaoUserQueryRequest userRequest = new FenxiaoUserQueryRequest();
        userRequest.setMobile(request.getPhoneNum() != null && !request.getPhoneNum().trim().isEmpty() ? request.getPhoneNum() : null);
        if (request.getMemberLevel() != null) {
            userRequest.setLevel(request.getMemberLevel());
        }
        fenXiaoQueryRequest.setStatus(FenXiaoStatus.未结算);
        BigDecimal waitIncome = iFenXiaoService.getSumFenxiao(fenXiaoQueryRequest,userRequest);
        walletAccountResponse.setCheckingCash(checkingCash);
        walletAccountResponse.setWaitCash(waitCash);
        walletAccountResponse.setWaitIncome(waitIncome);
        return walletAccountResponse;
    }

    /**
     * 获取待到账信息
     *
     * @param userIdList
     * @return
     */
//    public Map<Integer, BigDecimal> waitIncomeMap(String userIdList) {
//        List<FenXiaoReponse> waitIncomeList = iFenXiaoService.getSumFenXiaoByUids(Arrays.stream(userIdList.split(",")).map(j -> Integer.parseInt(j)).collect(Collectors.toList()));
//        return waitIncomeList.stream().collect(Collectors.toMap(FenXiaoReponse::getUid, FenXiaoReponse::getYongjin));
//    }

    /**
     * 获取用户可提现金额
     *
     * @param request
     * @return
     */
    public BigDecimal waitCash(WalletUserRequest request) {
        return userWalletMapper.WaitCashByUserId(request.getUserId());
    }

    public BigDecimal getDataFromMap(List<Map<String, Object>> list, Long userId) {
        for (Map<String, Object> map : list) {
            if (map != null && map.get("userId") != null && map.get("userId").equals(userId)) {
                BigDecimal alreadyCash = new BigDecimal(map.get("amount").toString());
                if(alreadyCash.compareTo(BigDecimal.ZERO)==-1){
                    alreadyCash = alreadyCash.negate();
                }
                return alreadyCash;
            }
        }
        return BigDecimal.ZERO;
    }


    /**
     * 资金账户导出
     *
     * @param request
     * @return
     */
    public ExportExcelCommonResponse<WalletAccountExport> excelExport(WalletAccountRequest request) {
        request.setPageSize(-1);
        WalletAccountResponse walletAccountResponse = accountList(request);
        List<WalletAccountList> list = walletAccountResponse.getRows();
        List<WalletAccountExport> result = new ArrayList<>();
        for(WalletAccountList walletAccountList:list){
            WalletAccountExport walletAccountExport = new WalletAccountExport();
            BeanUtils.copyProperties(walletAccountList,walletAccountExport);
            result.add(walletAccountExport);
        }
        ExportExcelCommonResponse<WalletAccountExport> response = new ExportExcelCommonResponse<>();
        response.setData(result);
        response.setFileName("WalletAccount.xlsx");
        return response;
    }

    /**
     * 会员等级字典
     *
     * @return
     */
    public Map<Integer, Object> memberLevel() {
        List<Map<String,Object>> list = iLevelConfigService.getLevelConfig().getData();
        Map<Integer,Object> map = new HashMap<>(list.size());
        for(Map<String,Object> m:list){
            map.put(Integer.parseInt(m.get("id").toString()),m.get("level_name"));
        }
        return map;
    }

    /**
     * 钱包类型字典
     *
     * @return
     */
    public Map<Object, Object> walletType() {
        WalletTypeEnum[] w = WalletTypeEnum.values();
        Map<Object, Object> map = new HashMap<>(w.length);
        for (WalletTypeEnum walletTypeEnum : w) {
            map.put(walletTypeEnum.getCode(), walletTypeEnum.getMsg());
        }
        return map;
    }

}
